/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.news.dao;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据访问BaseDao 
 * @author 科泰集团教研团队
 * @createTime 2024-4-17 20:49:54
 * @lastModify 2024-4-17 20:49:54
 * @version 1.0.0
 */
public class BaseDao {

     static String driver = null;
     static String url = null;
     static String username = null;
     static String password = null;

     static{
         // 获取配置文件的流
         InputStream is = BaseDao.class.getClassLoader()
                 .getResourceAsStream("database.properties");
         // 创建Properties类的对象
         Properties props = new Properties();
         try {
             // 加载配置
             props.load(is);
         } catch (Exception e) {
             e.printStackTrace();
         }
         driver = props.getProperty("driver");
         url = props.getProperty("url");
         username = props.getProperty("username");
         password = props.getProperty("password");
     }

     /**
     * 获取连接
     * @return
     */
    public Connection getConnection(){
        try {
            // 1、加载驱动
            Class.forName(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通用更新
     * @param sql
     * @param params
     * @return
     */
    public int executeUpdate(String sql, Object... params){
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            // 创建连接对象
            conn = getConnection();
            // 获取执行sql对象
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                stmt.setObject(i + 1, params[i]);
            }
            // 执行sql获得结果
            return stmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, stmt, null);
        }
        return 0;
    }


    /**
     * 关闭所有资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public void closeAll(Connection conn, Statement stmt, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
